#include "system_manager.h"
#include "scenes/scene_manager.h"
#include "control/control_api.h"
#include "device/device_manager.h"
#include "api/scene_api.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>

// 全局管理器实例
static scene_manager_t g_scene_manager;
static control_api_manager_t g_control_api_manager;
static device_manager_t g_device_manager;

// 在合适的位置添加这些辅助函数（如果不存在）
#ifndef EVENT_CREATE_DEFINED
event_t *event_create(event_type_t type, void *data, size_t data_len, void (*cleanup_fn)(void*)) {
    event_t *event = malloc(sizeof(event_t));
    if (!event) {
        return NULL;
    }

    event->type = type;
    event->data = data;
    event->data_len = data_len;
    event->cleanup_fn = cleanup_fn;
    event->source = NULL;

    return event;
}

void event_destroy(event_t *event) {
    if (event) {
        if (event->source) {
            free(event->source);
        }
        free(event);
    }
}
#define EVENT_CREATE_DEFINED
#endif

// 在数据更新事件处理函数中修复事件创建
static void handle_data_update_for_scenes(system_manager_t *manager, event_t *event) {
    char *key = (char *)event->data;

    // 获取新值
    json_t *value = data_pool_get(manager->data_pool, key);
    if (value) {
        // 检查值触发场景
        // scene_manager_check_value_triggers(&g_scene_manager, key, value);
        json_decref(value);
    }
}

// 在场景状态变化处理函数中修复事件创建
static void handle_scene_status_changed(system_manager_t *manager, event_t *event) {
    // 暂时简化实现，避免编译错误
    LOG_INFO("Scene status changed event received");
}

// 配置API路由处理函数
static http_response_t *config_api_get_global(const char *method, const char *path, 
                                             json_t *query_params, json_t *body, 
                                             void *user_data) {
    system_manager_t *sys_mgr = (system_manager_t *)user_data;
    
    json_t *config_json = json_object();
    json_object_set_new(config_json, "device_api_ip", json_string(sys_mgr->global_config.device_api_ip));
    json_object_set_new(config_json, "device_api_port", json_integer(sys_mgr->global_config.device_api_port));
    json_object_set_new(config_json, "http_server_ip", json_string(sys_mgr->global_config.http_server_ip));
    json_object_set_new(config_json, "http_server_port", json_integer(sys_mgr->global_config.http_server_port));
    json_object_set_new(config_json, "device_poll_interval", json_integer(sys_mgr->global_config.device_poll_interval));
    json_object_set_new(config_json, "debug_mode", json_boolean(sys_mgr->global_config.debug_mode));
    json_object_set_new(config_json, "log_level", json_string(sys_mgr->global_config.log_level));
    
    return http_response_json(200, config_json);
}

static http_response_t *config_api_update_global(const char *method, const char *path, 
                                                json_t *query_params, json_t *body, 
                                                void *user_data) {
    system_manager_t *sys_mgr = (system_manager_t *)user_data;
    
    if (!body || !json_is_object(body)) {
        return http_response_error(400, "Invalid request body");
    }
    
    bool config_changed = false;
    
    // 更新设备API配置
    json_t *device_api_ip = json_object_get(body, "device_api_ip");
    json_t *device_api_port = json_object_get(body, "device_api_port");
    
    if (device_api_ip && json_is_string(device_api_ip)) {
        const char *new_ip = json_string_value(device_api_ip);
        if (strcmp(sys_mgr->global_config.device_api_ip, new_ip) != 0) {
            global_config_set_device_api(&sys_mgr->global_config, new_ip, 
                                       sys_mgr->global_config.device_api_port);
            config_changed = true;
        }
    }
    
    if (device_api_port && json_is_integer(device_api_port)) {
        int new_port = json_integer_value(device_api_port);
        if (sys_mgr->global_config.device_api_port != new_port) {
            global_config_set_device_api(&sys_mgr->global_config, 
                                       sys_mgr->global_config.device_api_ip, new_port);
            config_changed = true;
        }
    }
    
    // 保存配置到数据库
    if (config_changed) {
        global_config_save(&sys_mgr->global_config, sys_mgr->db_mgr);
        
        // 重启设备管理器以应用新配置
        device_manager_cleanup(&g_device_manager);
        const char *base_url = global_config_get_device_api_base_url(&sys_mgr->global_config);
        device_manager_init(&g_device_manager, base_url, sys_mgr->event_loop, 
                           sys_mgr->timer, sys_mgr->data_pool);
        device_manager_start_polling(&g_device_manager, sys_mgr->global_config.device_poll_interval);
    }
    
    json_t *response_json = json_object();
    json_object_set_new(response_json, "message", json_string("Configuration updated successfully"));
    json_object_set_new(response_json, "config_changed", json_boolean(config_changed));
    
    return http_response_json(200, response_json);
}

// 注册配置API路由
static int config_api_register_routes(http_server_t *server) {
    http_server_add_route(server, "GET", "/api/config/global", config_api_get_global);
    http_server_add_route(server, "PUT", "/api/config/global", config_api_update_global);
    return SUCCESS;
}

int system_manager_init(system_manager_t *manager) {
    if (!manager) {
        return ERROR_INVALID_PARAM;
    }
    
    memset(manager, 0, sizeof(system_manager_t));
    
    // 初始化全局配置
    if (global_config_init(&manager->global_config) != SUCCESS) {
        LOG_ERROR("Failed to init global config");
        goto error;
    }
    
    // 初始化数据库管理器
    manager->db_mgr = malloc(sizeof(db_manager_t));
    if (db_manager_init(manager->db_mgr, "system.db") != SUCCESS) {
        LOG_ERROR("Failed to init database manager");
        goto error;
    }
    
    // 从数据库加载全局配置
    global_config_load(&manager->global_config, manager->db_mgr);
    
    // 初始化事件循环
    manager->event_loop = malloc(sizeof(event_loop_t));
    if (event_loop_init(manager->event_loop, "main", MAX_EVENTS) != SUCCESS) {
        LOG_ERROR("Failed to init event loop");
        goto error;
    }
    
    // 初始化配置管理器
    manager->config = malloc(sizeof(config_manager_t));
    if (config_manager_init(manager->config, manager->db_mgr, true) != SUCCESS) {
        LOG_ERROR("Failed to init config manager");
        goto error;
    }
    
    // 初始化数据池
    manager->data_pool = malloc(sizeof(data_pool_t));
    json_t *pool_config = config_manager_get(manager->config, "data_pool.max_size");
    size_t max_size = json_integer_value(pool_config) ?: 1000;
    if (data_pool_init(manager->data_pool, max_size, manager->event_loop, manager->db_mgr) != SUCCESS) {
        LOG_ERROR("Failed to init data pool");
        goto error;
    }
    
    // 初始化定时器管理器
    manager->timer = malloc(sizeof(timer_manager_t));
    if (timer_manager_init(manager->timer, manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to init timer manager");
        goto error;
    }
    
    // 初始化设备管理器（使用可配置的IP）
    const char *base_url = global_config_get_device_api_base_url(&manager->global_config);
    if (device_manager_init(&g_device_manager, base_url, manager->event_loop, 
                           manager->timer, manager->data_pool) != SUCCESS) {
        LOG_ERROR("Failed to init device manager");
        goto error;
    }
    
    // 启动设备数据轮询
    if (device_manager_start_polling(&g_device_manager, manager->global_config.device_poll_interval) != SUCCESS) {
        LOG_ERROR("Failed to start device polling");
        goto error;
    }
    
    // 初始化控制API管理器并设置设备管理器
    if (control_api_manager_init(&g_control_api_manager, manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to init control API manager");
        goto error;
    }
    control_api_set_device_manager(&g_device_manager);
    
    // 初始化场景管理器
    if (scene_manager_init(&g_scene_manager, manager->db_mgr, manager->event_loop, 
                          manager->timer, manager->data_pool) != SUCCESS) {
        LOG_ERROR("Failed to init scene manager");
        goto error;
    }
    
    // 初始化HTTP服务器
    if (http_server_init(&manager->http_server, manager->global_config.http_server_ip, 
                        manager->global_config.http_server_port, manager) != SUCCESS) {
        LOG_ERROR("Failed to init HTTP server");
        goto error;
    }
    
    // 注册API路由
    scene_api_register_routes(&manager->http_server);
    config_api_register_routes(&manager->http_server);
    
    // 启动HTTP服务器
    if (http_server_start(&manager->http_server) != SUCCESS) {
        LOG_ERROR("Failed to start HTTP server");
        goto error;
    }
    
    // 注册事件处理器
    event_loop_register_handler(manager->event_loop, EVENT_API_RESPONSE, 
                               (event_handler_t)system_manager_handle_api_response);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_UPDATE, 
                               (event_handler_t)system_manager_handle_data_update);
    event_loop_register_handler(manager->event_loop, EVENT_TIMER_TRIGGER, 
                               (event_handler_t)system_manager_handle_timer_trigger);
    event_loop_register_handler(manager->event_loop, EVENT_DATA_CHECK, 
                               (event_handler_t)system_manager_handle_data_check);
    event_loop_register_handler(manager->event_loop, EVENT_DB_UPDATE, 
                               (event_handler_t)system_manager_handle_db_update);
    event_loop_register_handler(manager->event_loop, EVENT_SCENE_STATUS_CHANGED, 
                               (event_handler_t)system_manager_handle_scene_status_changed);
    
    // 启动事件循环
    if (event_loop_start(manager->event_loop) != SUCCESS) {
        LOG_ERROR("Failed to start event loop");
        goto error;
    }
    
    // 记录系统启动状态到数据库
    json_t *status_details = json_object();
    json_object_set_new(status_details, "version", json_string("1.0.0"));
    json_object_set_new(status_details, "start_time", json_integer(time(NULL)));
    json_object_set_new(status_details, "device_api_url", json_string(base_url));
    json_object_set_new(status_details, "http_server", 
                       json_string(manager->global_config.http_server_ip));
    json_object_set_new(status_details, "http_port", 
                       json_integer(manager->global_config.http_server_port));
    
    db_system_status_set(manager->db_mgr, "system_manager", "running", status_details);
    json_decref(status_details);
    
    manager->initialized = true;
    manager->running = true;
    
    LOG_INFO("System manager initialized successfully");
    LOG_INFO("Device API: %s", base_url);
    LOG_INFO("HTTP API: http://%s:%d", manager->global_config.http_server_ip, 
             manager->global_config.http_server_port);
    
    return SUCCESS;

error:
    system_manager_cleanup(manager);
    return ERROR_INVALID_PARAM;
}

int system_manager_update_device_api_config(system_manager_t *manager, const char *ip, int port) {
    if (!manager || !manager->initialized || !ip || port <= 0) {
        return ERROR_INVALID_PARAM;
    }

    // 停止设备轮询
    device_manager_stop_polling(&g_device_manager);
    
    // 更新配置
    global_config_set_device_api(&manager->global_config, ip, port);
    global_config_save(&manager->global_config, manager->db_mgr);
    
    // 重新初始化设备管理器
    device_manager_cleanup(&g_device_manager);
    
    const char *base_url = global_config_get_device_api_base_url(&manager->global_config);
    if (device_manager_init(&g_device_manager, base_url, manager->event_loop, 
                           manager->timer, manager->data_pool) != SUCCESS) {
        LOG_ERROR("Failed to reinit device manager with new config");
        return ERROR_INVALID_PARAM;
    }
    
    // 重新启动设备轮询
    if (device_manager_start_polling(&g_device_manager, manager->global_config.device_poll_interval) != SUCCESS) {
        LOG_ERROR("Failed to restart device polling");
        return ERROR_INVALID_PARAM;
    }
    
    LOG_INFO("Device API configuration updated: %s", base_url);
    return SUCCESS;
}

int system_manager_update_http_server_config(system_manager_t *manager, const char *ip, int port) {
    if (!manager || !manager->initialized || !ip || port <= 0) {
        return ERROR_INVALID_PARAM;
    }

    // 更新配置
    global_config_set_http_server(&manager->global_config, ip, port);
    global_config_save(&manager->global_config, manager->db_mgr);
    
    LOG_INFO("HTTP server configuration updated: %s:%d", ip, port);
    return SUCCESS;
}

int system_manager_restart_http_server(system_manager_t *manager) {
    if (!manager || !manager->initialized) {
        return ERROR_INVALID_PARAM;
    }

    // 停止HTTP服务器
    http_server_stop(&manager->http_server);
    
    // 重新初始化HTTP服务器
    http_server_cleanup(&manager->http_server);
    
    if (http_server_init(&manager->http_server, manager->global_config.http_server_ip, 
                        manager->global_config.http_server_port, manager) != SUCCESS) {
        LOG_ERROR("Failed to reinit HTTP server");
        return ERROR_INVALID_PARAM;
    }
    
    // 重新注册路由
    scene_api_register_routes(&manager->http_server);
    config_api_register_routes(&manager->http_server);
    
    // 重新启动HTTP服务器
    if (http_server_start(&manager->http_server) != SUCCESS) {
        LOG_ERROR("Failed to restart HTTP server");
        return ERROR_INVALID_PARAM;
    }
    
    LOG_INFO("HTTP server restarted on http://%s:%d", 
             manager->global_config.http_server_ip, manager->global_config.http_server_port);
    return SUCCESS;
}

void system_manager_cleanup(system_manager_t *manager) {
    if (!manager) {
        return;
    }
    
    system_manager_stop(manager);
    
    // 记录系统停止状态到数据库
    if (manager->db_mgr && manager->db_mgr->initialized) {
        json_t *status_details = json_object();
        json_object_set_new(status_details, "stop_time", json_integer(time(NULL)));
        db_system_status_set(manager->db_mgr, "system_manager", "stopped", status_details);
        json_decref(status_details);
    }
    
    // 清理场景管理器
    scene_manager_destroy(&g_scene_manager);
    
    // 清理控制API管理器
    control_api_manager_cleanup(&g_control_api_manager);
    
    // 清理设备管理器
    device_manager_cleanup(&g_device_manager);
    
    // 清理HTTP服务器
    http_server_cleanup(&manager->http_server);
    
    // 清理全局配置
    global_config_cleanup(&manager->global_config);
    
    if (manager->timer) {
        timer_manager_destroy(manager->timer);
        free(manager->timer);
    }
    
    if (manager->data_pool) {
        data_pool_destroy(manager->data_pool);
        free(manager->data_pool);
    }
    
    if (manager->config) {
        config_manager_destroy(manager->config);
        free(manager->config);
    }
    
    if (manager->event_loop) {
        event_loop_cleanup(manager->event_loop);
        free(manager->event_loop);
    }
    
    if (manager->db_mgr) {
        db_manager_close(manager->db_mgr);
        free(manager->db_mgr);
    }
    
    manager->initialized = false;
}
